<template>
  <div class="calc-goal-container">
    <!-- 一、课程基本情况 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="section-title">一、课程基本情况</span>
        </div>
      </template>
      
      <el-form :model="courseInfo" label-width="120px" ref="courseFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="courseInfo.courseName" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程代码" prop="courseCode">
              <el-input v-model="courseInfo.courseCode" placeholder="请输入课程代码" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="学期" prop="semester">
              <el-input v-model="courseInfo.semester" placeholder="如：2024-2025学年春季学期" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年级" prop="grade">
              <el-input-number 
                v-model="courseInfo.grade" 
                :min="2000" 
                :max="2100"
                :precision="0"
                placeholder="如：2024"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="班级" prop="className">
              <el-input v-model="courseInfo.className" placeholder="请输入班级" />
            </el-form-item>
          </el-col>
        </el-row>
        
                 <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="适用专业" prop="applicableMajor">
               <el-input v-model="courseInfo.applicableMajor" placeholder="请输入适用专业" />
             </el-form-item>
           </el-col>
         </el-row>
      </el-form>
    </el-card>

    <!-- 二、课程目标与毕业要求的对应关系 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="section-title">二、课程目标与毕业要求的对应关系</span>
          <div class="header-buttons">
            <el-button type="danger" @click="clearAllGoalRelations" :icon="Delete">清空对应关系</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="goalRelations.length === 0" class="empty-state">
        <el-empty description="暂无课程目标与毕业要求的对应关系，请点击下方按钮添加" />
      </div>
      
      <div v-else>
        <div v-for="(relation, index) in goalRelations" :key="index" class="goal-relation-item">
          <el-card class="relation-card">
            <template #header>
              <div class="relation-header">
                <span class="relation-number">序号：{{ relation.number }}</span>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeGoalRelation(index)"
                  :icon="Delete"
                >
                  删除
                </el-button>
              </div>
            </template>
            
            <el-form :model="relation" label-width="140px">
              <el-form-item label="课程目标" prop="courseGoal">
                <el-input 
                  v-model="relation.courseGoal" 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入课程目标，例如：熟悉Matlab软件的操作窗口和操作方法；掌握运用Matlab软件进行程序设计的基本方法"
                />
              </el-form-item>
              

              
              <el-form-item label="毕业要求指标点" prop="graduationRequirementPoints">
                 <div v-for="(point, pointIndex) in relation.graduationRequirementPoints" :key="point.id" class="graduation-requirement-point-item">
                   <div class="point-header">
                     <span class="point-number">指标点 {{ pointIndex + 1 }}</span>
                     <el-button 
                       type="danger" 
                       size="small" 
                       @click="removeGraduationRequirementPoint(index, pointIndex)"
                       :icon="Delete"
                     >
                       删除指标点
                     </el-button>
                   </div>
                   
                   <div class="point-content">
                     <div class="point-field">
                       <label class="field-label">毕业要求编号：</label>
                       <el-input-number 
                         v-model="point.graduationRequirementNumber" 
                         :min="1" 
                         :precision="0"
                         placeholder="如：3"
                         style="width: 120px"
                       />
                     </div>
                     
                     <div class="point-field">
                       <label class="field-label">毕业要求描述：</label>
                       <el-input 
                         v-model="point.graduationRequirementDescription" 
                         placeholder="请输入毕业要求描述，例如：学科素养"
                         style="width: 100%"
                       />
                     </div>
                     
                     <div class="point-field">
                       <label class="field-label">指标点编号：</label>
                       <el-input 
                         v-model="point.graduationRequirementPointNumber" 
                         placeholder="如：3.2"
                         @input="() => validatePointNumber(index, pointIndex)"
                         style="width: 120px"
                       />
                     </div>
                     
                     <div class="point-field">
                       <label class="field-label">指标点描述：</label>
                       <el-input 
                         v-model="point.graduationRequirementPointDescription" 
                         type="textarea" 
                         :rows="3"
                         placeholder="请输入毕业要求指标点描述，例如：学科综合。了解数学与计算机科学、金融经济等学科的联系，具有整合和利用数学及相关学科知识解决一些实际问题的意识和能力。"
                         style="width: 100%"
                       />
                     </div>
                     
                     <div class="point-field">
                       <label class="field-label">支撑度：</label>
                       <el-radio-group v-model="point.supportLevel">
                         <el-radio value="H">高(H)</el-radio>
                         <el-radio value="M">中(M)</el-radio>
                         <el-radio value="L">低(L)</el-radio>
                       </el-radio-group>
                     </div>
                   </div>
                   
                   <div v-if="point.pointNumberError" class="error-message">
                     {{ point.pointNumberError }}
                   </div>
                 </div>
               </el-form-item>
              




              

            </el-form>
            
            <!-- 检查按钮和结果显示 -->
            <div class="check-section">
              <div class="button-group">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="checkGoalRelation(index)"
                  :icon="Check"
                >
                  检查
                </el-button>
                
                <el-button 
                  type="success" 
                  size="small" 
                  @click="addGraduationRequirementPoint(index)"
                  :icon="Plus"
                >
                  添加指标点
                </el-button>
              </div>
              
              <div v-if="relation.checkResult" class="check-result">
                <div v-if="relation.checkResult.success" class="check-success">
                  {{ relation.checkResult.message }}
                </div>
                <div v-else class="check-error">
                  {{ relation.checkResult.message }}
                </div>
              </div>
            </div>

          </el-card>
        </div>

         <!-- 全局检查按钮 -->
         <div class="global-check-section">
          <el-button 
            type="warning" 
            size="large" 
            @click="checkAllGoalRelations"
            :icon="Check"
          >
            检查所有对应关系
          </el-button>
          
          <div v-if="globalCheckResult" class="global-check-result">
            <div v-if="globalCheckResult.success" class="check-success">
              {{ globalCheckResult.message }}
            </div>
            <div v-else class="check-error">
              {{ globalCheckResult.message }}
            </div>
          </div>
        </div>
        
        <!-- 生成对应表按钮 -->
        <div class="generate-correspondence-table-section">
          <el-button 
            type="primary" 
            size="large" 
            @click="generateCorrespondenceTable"
            :icon="Document"
            :disabled="!globalCheckResult || !globalCheckResult.success"
          >
            生成课程目标与毕业要求指标点对应表
          </el-button>
        </div>
        
        <!-- 生成的对应表 -->
        <div v-if="correspondenceTable" class="correspondence-table-container">
          <h3>课程目标与毕业要求指标点对应表：</h3>
          <div class="table-wrapper">
            <table class="correspondence-table">
              <thead>
                <tr>
                  <th>课程目标</th>
                  <th>毕业要求指标点</th>
                  <th>毕业要求</th>
                  <th>权重</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(relation, index) in goalRelations" :key="index">
                  <td>课程目标{{ relation.number }}：{{ relation.courseGoal }}</td>
                  <td>
                    <div v-for="(point, pointIndex) in relation.graduationRequirementPoints" :key="point.id" class="table-point-item">
                      <div class="point-main">{{ point.graduationRequirementPointNumber }}：{{ point.graduationRequirementPointDescription }}</div>
                      <div class="point-support">支撑度：{{ point.supportLevel }}</div>
                    </div>
                  </td>
                  <td>
                    <div v-for="(point, pointIndex) in relation.graduationRequirementPoints" :key="point.id" class="table-requirement-item">
                      {{ point.graduationRequirementNumber }}.{{ point.graduationRequirementDescription }}
                    </div>
                  </td>
                  <td>{{ relation.weight }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- 添加对应关系按钮 -->
      <div class="add-relation-section">
        <el-button 
          type="primary" 
          size="large" 
          @click="addGoalRelation" 
          :icon="Plus"
        >
          添加对应关系
        </el-button>
      </div>
    </el-card>

    <!-- 三、评分标准 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="section-title">三、评分标准</span>
        </div>
      </template>
      
      <div class="scoring-section">
        <el-button 
          type="success" 
          size="large" 
          @click="generateAIPrompts"
          :icon="MagicStick"
          :loading="generating"
        >
          开始生成AI提示词
        </el-button>
        
        <div v-if="aiPrompts.length > 0" class="prompts-container">
          <h3>生成的AI提示词：</h3>
          <div v-for="(prompt, index) in aiPrompts" :key="index" class="prompt-item">
            <el-card class="prompt-card">
              <template #header>
                <div class="prompt-header">
                  <span>课程目标 {{ prompt.goalNumber }}</span>
                  <el-button 
                    type="primary" 
                    size="small" 
                    @click="copyPrompt(prompt.text)"
                    :icon="CopyDocument"
                  >
                    复制
                  </el-button>
                </div>
              </template>
              <div class="prompt-content">{{ prompt.text }}</div>
            </el-card>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 四、评价方法 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="section-title">四、评价方法</span>
          <div class="header-buttons">
            <el-button type="danger" @click="clearAllEvaluationMethods" :icon="Delete">清空评价方法</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="evaluationMethods.length === 0" class="empty-state">
        <el-empty description="暂无评价方法，请点击下方按钮添加" />
      </div>
      
      <div v-else>
        <div v-for="(method, index) in evaluationMethods" :key="index" class="evaluation-method-item">
          <el-card class="method-card">
            <template #header>
              <div class="method-header">
                <span class="method-number">序号：{{ method.number }}</span>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="removeEvaluationMethod(index)"
                  :icon="Delete"
                >
                  删除
                </el-button>
              </div>
            </template>
            
            <el-form :model="method" label-width="140px">
              <el-form-item label="评价方法名称" prop="methodName">
                <el-input 
                  v-model="method.methodName" 
                  placeholder="请输入评价方法名称，例如：课堂参与、期末考核"
                />
              </el-form-item>
              
              <el-form-item label="是否过程性考核" prop="isProcessEvaluation">
                <el-radio-group v-model="method.isProcessEvaluation">
                  <el-radio :value="true">是</el-radio>
                  <el-radio :value="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="比例" prop="percentage">
                <el-input-number 
                  v-model="method.percentage" 
                  :min="0" 
                  :max="100"
                  :precision="0"
                  placeholder="请输入0-100之间的整数"
                  style="width: 200px"
                />
              </el-form-item>
              
              <!-- 目标点比重表格 -->
              <el-form-item label="目标点比重" prop="goalWeights">
                <div class="goal-weights-table-container">
                  <table class="goal-weights-table">
                    <thead>
                      <tr>
                        <th>课程目标</th>
                        <th>比重（%）</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="(goal, goalIndex) in goalRelations" :key="goalIndex">
                        <td>课程目标{{ goal.number }}：{{ goal.courseGoal }}</td>
                        <td>
                          <el-input-number 
                            v-model="method.goalWeights[goalIndex]" 
                            :min="0" 
                            :max="100"
                            :precision="0"
                            placeholder="0-100"
                            style="width: 100px"
                            @change="validateGoalWeights(index)"
                          />
                        </td>
                      </tr>
                    </tbody>
                  </table>
                  <div class="goal-weights-total">
                    总比重：{{ getGoalWeightsTotal(method.goalWeights) }}%
                    <span v-if="getGoalWeightsTotal(method.goalWeights) !== 100" class="weight-error">
                      （总比重应等于100%）
                    </span>
                  </div>
                </div>
              </el-form-item>
              
              <el-form-item label="评价依据" prop="evaluationBasis">
                <el-input 
                  v-model="method.evaluationBasis" 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入评价依据"
                />
              </el-form-item>
            </el-form>
          </el-card>
        </div>
        
        <!-- 检查按钮 -->
        <div class="evaluation-check-section">
          <el-button 
            type="warning" 
            size="large" 
            @click="checkEvaluationMethods"
            :icon="Check"
          >
            检查评价方法
          </el-button>
          
          <div v-if="evaluationCheckResult" class="evaluation-check-result">
            <div v-if="evaluationCheckResult.success" class="check-success">
              {{ evaluationCheckResult.message }}
            </div>
            <div v-else class="check-error">
              {{ evaluationCheckResult.message }}
            </div>
          </div>
        </div>
        
        <!-- 生成表格按钮 -->
        <div class="generate-table-section">
          <el-button 
            type="success" 
            size="large" 
            @click="generateEvaluationTable"
            :icon="Document"
            :disabled="!evaluationCheckResult || !evaluationCheckResult.success"
          >
            生成评价方法表格
          </el-button>
        </div>
        
        <!-- 生成的表格 -->
        <div v-if="evaluationTable" class="evaluation-table-container">
          <h3>评价方法表格：</h3>
          <div class="table-wrapper">
            <table class="evaluation-table">
              <thead>
                <tr>
                  <th colspan="3">评价方法</th>
                  <th rowspan="2">评价依据（百分制）</th>
                </tr>
                <tr>
                  <th colspan="2">定量评价</th>
                  <th>比例（%）</th>
                </tr>
              </thead>
              <tbody>
                <!-- 过程性考核项 -->
                <template v-for="(method, index) in processEvaluationMethods" :key="`process-${index}`">
                  <tr>
                    <td :rowspan="processEvaluationMethods.length" v-if="index === 0" class="process-evaluation-cell">过程性考核</td>
                    <td>{{ method.methodName }}</td>
                    <td>{{ method.percentage }}</td>
                    <td>{{ method.evaluationBasis }}</td>
                  </tr>
                </template>
                
                <!-- 非过程性考核项 -->
                <template v-for="(method, index) in nonProcessEvaluationMethods" :key="`non-process-${index}`">
                  <tr>
                    <td colspan="2">{{ method.methodName }}</td>
                    <td>{{ method.percentage }}</td>
                    <td>{{ method.evaluationBasis }}</td>
                  </tr>
                </template>
                <!-- 总评成绩行 -->
                <tr class="total-row">
                  <td colspan="2">总评成绩</td>
                  <td>100</td>
                  <td>{{ totalEvaluationFormula }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- 添加评价方法按钮 -->
      <div class="add-evaluation-method-section">
        <el-button 
          type="primary" 
          size="large" 
          @click="addEvaluationMethod" 
          :icon="Plus"
        >
          添加评价方法
        </el-button>
      </div>
    </el-card>

    <!-- 五、达成度计算 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="section-title">五、达成度计算</span>
        </div>
      </template>
      
      <div class="achievement-calculation-section">
        <div class="file-operations">
          <el-button 
            type="primary" 
            size="large" 
            @click="downloadTemplate"
            :icon="Download"
            :disabled="evaluationMethods.length === 0"
          >
            下载模板
          </el-button>
          
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            accept=".xlsx"
            class="upload-button"
          >
            <el-button 
              type="success" 
              size="large" 
              :icon="Upload"
            >
              上传数据
            </el-button>
          </el-upload>
        </div>
        
        <div class="upload-tips">
          <h4>上传要求：</h4>
          <ul>
            <li>必须上传xlsx格式的文件</li>
            <li>上传的xlsx文件可以增加列，但是不要修改模板中已有列的名称</li>
            <li>不要修改sheet的名称</li>
            <li>表头格式为"评价方法$目标序号"，例如"期末考试$目标1"</li>
            <li>每个评价方法对应每个课程目标的分值，每项分值不用是百分制，每个评价方法的加总分数最高是100分</li>
            <li>例如：期末考试占总成绩的60%，目标1占期末考试的40%，目标2占期末考试的60%，那么期末考试$目标1的满分是40分，期末考试$目标2的满分是60分</li>
          </ul>
        </div>
        
        <!-- 计算结果表格 -->
        <GoalTable 
          v-if="goalResults.length > 0"
          :goal-results="goalResults"
          :evaluation-methods="processedEvaluationMethods"
          :overall-achievement="parseFloat(overallAchievement)"
        />
      </div>
    </el-card>

    <!-- 六、达成度图表 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="section-title">六、达成度图表</span>
        </div>
      </template>
      
      <div class="achievement-charts-section">
        <div v-if="!canGenerateCharts" class="charts-prerequisite">
          <el-alert
            title="请先完成前五步"
            description="生成图表需要先完成课程目标设置、评价方法配置和数据上传等步骤"
            type="warning"
            :closable="false"
            show-icon
          />
        </div>
        
        <div v-else>
          <!-- 6.1 课程目标评价达成值 -->
          <div class="chart-section">
            <h3>6.1 课程目标评价达成值</h3>
            <DrawGoal 
              :goal-results="goalResults"
              :student-data="studentData"
              :evaluation-methods="evaluationMethods"
              :data-headers="dataHeaders"
              :achievement-standard="achievementStandard"
              chart-type="achievement-bar"
            />
          </div>
          
          <!-- 6.2 课程目标达成分布图 -->
          <div class="chart-section">
            <h3>6.2 课程目标达成分布图</h3>
            <DrawGoal 
              :goal-results="goalResults"
              :student-data="studentData"
              :evaluation-methods="evaluationMethods"
              :data-headers="dataHeaders"
              v-model:achievement-standard="achievementStandard"
              chart-type="achievement-scatter"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 七、课程目标考核合理性审核表 -->
    <el-card class="section-card">
      <template #header>
        <div class="card-header">
          <span class="section-title">七、课程目标考核合理性审核表</span>
        </div>
      </template>
      
      <div class="goal-audit-section">
        <div v-if="!canGenerateAudit" class="audit-prerequisite">
          <el-alert
            title="请先完成前六步"
            description="生成审核表需要先完成课程目标设置、评价方法配置、达成度计算等步骤"
            type="warning"
            :closable="false"
            show-icon
          />
        </div>
        
        <div v-else>
          <GoalAudit 
            :key="`audit-${achievementStandard}`"
            :course-info="courseInfo"
            :goal-relations="goalRelations"
            :evaluation-methods="evaluationMethods"
            :goal-results="goalResults"
            :total-evaluation-formula="totalEvaluationFormula"
            :achievement-standard="achievementStandard"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, MagicStick, CopyDocument, Check, Document, Download, Upload } from '@element-plus/icons-vue'
import GoalTable from './GoalTable.vue'
import DrawGoal from './DrawGoal.vue'
import GoalAudit from './GoalAudit.vue'

// 课程基本信息
const courseInfo = reactive({
  courseName: '',
  courseCode: '',
  semester: '',
  grade: null,
  className: '',
  applicableMajor: ''
})

// 课程目标与毕业要求的对应关系
const goalRelations = ref([])

// AI提示词
const aiPrompts = ref([])
const generating = ref(false)

// 全局检查结果
const globalCheckResult = ref(null)

// 评价方法相关
const evaluationMethods = ref([])
const evaluationCheckResult = ref(null)
const evaluationTable = ref(null)
const totalEvaluationFormula = ref('')

// 对应表相关
const correspondenceTable = ref(null)

// 达成度计算相关
const goalResults = ref([])
const processedEvaluationMethods = ref([])
const overallAchievement = ref(0)
const uploadRef = ref()
const studentData = ref([]) // 学生数据
const dataHeaders = ref([]) // 数据表头
const achievementStandard = ref(0.6) // 共享的达成标准

// 计算属性：分离过程性和非过程性考核项
const processEvaluationMethods = computed(() => {
  return evaluationMethods.value.filter(method => method.isProcessEvaluation)
})

const nonProcessEvaluationMethods = computed(() => {
  return evaluationMethods.value.filter(method => !method.isProcessEvaluation)
})

// 检查是否可以生成图表
const canGenerateCharts = computed(() => {
  return goalRelations.value.length > 0 && 
         evaluationMethods.value.length > 0 && 
         goalResults.value.length > 0 &&
         studentData.value.length > 0
})

// 检查是否可以生成审核表
const canGenerateAudit = computed(() => {
  return goalRelations.value.length > 0 && 
         evaluationMethods.value.length > 0 && 
         goalResults.value.length > 0 &&
         studentData.value.length > 0
})

// 表单引用
const courseFormRef = ref()



// 添加课程目标与毕业要求的对应关系
const addGoalRelation = () => {
  const newRelation = {
    number: goalRelations.value.length + 1,
    courseGoal: '',
    // 修改为数组结构，支持多个指标点
    graduationRequirementPoints: [],
    checkResult: null
  }
  goalRelations.value.push(newRelation)
}

// 添加毕业要求指标点到指定课程目标
const addGraduationRequirementPoint = (goalIndex) => {
  const goal = goalRelations.value[goalIndex]
  
  // 确保 graduationRequirementPoints 数组存在
  if (!goal.graduationRequirementPoints) {
    goal.graduationRequirementPoints = []
  }
  
  const newPoint = {
    id: Date.now() + Math.random(), // 生成唯一ID
    graduationRequirementNumber: null,
    graduationRequirementDescription: '',
    graduationRequirementPointNumber: '',
    graduationRequirementPointDescription: '',
    supportLevel: '',
    pointNumberError: ''
  }
  goal.graduationRequirementPoints.push(newPoint)
}

// 删除毕业要求指标点
const removeGraduationRequirementPoint = (goalIndex, pointIndex) => {
  const goal = goalRelations.value[goalIndex]
  if (goal.graduationRequirementPoints && goal.graduationRequirementPoints.length > pointIndex) {
    goal.graduationRequirementPoints.splice(pointIndex, 1)
  }
}

// 删除课程目标与毕业要求的对应关系
const removeGoalRelation = (index) => {
  ElMessageBox.confirm('确定要删除这个对应关系吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    goalRelations.value.splice(index, 1)
    // 重新排序序号
    goalRelations.value.forEach((relation, idx) => {
      relation.number = idx + 1
    })
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

// 清空所有课程目标与毕业要求的对应关系
const clearAllGoalRelations = () => {
  if (goalRelations.value.length === 0) {
    ElMessage.warning('当前没有对应关系数据')
    return
  }
  
  ElMessageBox.confirm('确定要清空所有对应关系吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定清空',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger'
  }).then(() => {
    goalRelations.value = []
    // 清除相关的结果
    globalCheckResult.value = null
    correspondenceTable.value = null
    ElMessage.success('所有对应关系已清空')
  }).catch(() => {
    // 用户取消清空
  })
}

// 验证毕业要求指标点编号
const validatePointNumber = (goalIndex, pointIndex) => {
  const goal = goalRelations.value[goalIndex]
  if (!goal || !goal.graduationRequirementPoints || !goal.graduationRequirementPoints[pointIndex]) {
    return
  }
  
  const point = goal.graduationRequirementPoints[pointIndex]
  const pointNumber = point.graduationRequirementPointNumber
  const requirementNumber = point.graduationRequirementNumber
  
  if (!pointNumber || !requirementNumber) {
    point.pointNumberError = ''
    return
  }
  
  // 检查格式是否为 x.y 的形式
  const pointPattern = /^\d+\.\d+$/
  if (!pointPattern.test(pointNumber)) {
    point.pointNumberError = '毕业要求指标点格式应为 x.y 的形式，如 3.2'
    return
  }
  
  // 检查主编号是否匹配
  const pointMainNumber = parseInt(pointNumber.split('.')[0])
  if (pointMainNumber !== requirementNumber) {
    point.pointNumberError = `毕业要求指标点 ${pointNumber} 与毕业要求 ${requirementNumber} 不匹配`
    return
  }
  
  // 检查是否重复（在所有课程目标中）
  const isDuplicate = checkPointNumberDuplicate(pointNumber, goalIndex, pointIndex)
  if (isDuplicate) {
    point.pointNumberError = `毕业要求指标点 ${pointNumber} 已存在，不能重复`
    return
  }
  
  point.pointNumberError = ''
}

// 检查指标点编号是否重复
const checkPointNumberDuplicate = (pointNumber, currentGoalIndex, currentPointIndex) => {
  for (let goalIndex = 0; goalIndex < goalRelations.value.length; goalIndex++) {
    const goal = goalRelations.value[goalIndex]
    if (!goal.graduationRequirementPoints) {
      continue
    }
    
    for (let pointIndex = 0; pointIndex < goal.graduationRequirementPoints.length; pointIndex++) {
      // 跳过当前正在验证的点
      if (goalIndex === currentGoalIndex && pointIndex === currentPointIndex) {
        continue
      }
      
      const point = goal.graduationRequirementPoints[pointIndex]
      if (point && point.graduationRequirementPointNumber === pointNumber) {
        return true
      }
    }
  }
  return false
}

// 检查单个课程目标对应关系
const checkGoalRelation = (index) => {
  const relation = goalRelations.value[index]
  
  // 检查基本信息是否完整
  if (!relation.courseGoal) {
    relation.checkResult = {
      success: false,
      message: '请完善课程目标信息'
    }
    return
  }
  
  // 检查是否有指标点
  if (!relation.graduationRequirementPoints || relation.graduationRequirementPoints.length === 0) {
    relation.checkResult = {
      success: false,
      message: '请至少添加一个毕业要求指标点'
    }
    return
  }
  
  // 检查每个指标点是否完整
  for (let i = 0; i < relation.graduationRequirementPoints.length; i++) {
    const point = relation.graduationRequirementPoints[i]
    if (!point.graduationRequirementNumber || 
        !point.graduationRequirementDescription ||
        !point.graduationRequirementPointNumber || 
        !point.graduationRequirementPointDescription || 
        !point.supportLevel) {
      relation.checkResult = {
        success: false,
        message: `第${i + 1}个指标点信息不完整，请检查`
      }
      return
    }
    
    if (point.pointNumberError) {
      relation.checkResult = {
        success: false,
        message: `第${i + 1}个指标点：${point.pointNumberError}`
      }
      return
    }
  }
  
  relation.checkResult = {
    success: true,
    message: '检查通过'
  }
}

// 检查所有课程目标对应关系
const checkAllGoalRelations = () => {
  // 先检查每个对应关系
  let allValid = true
  
  for (let i = 0; i < goalRelations.value.length; i++) {
    const relation = goalRelations.value[i]
    
    // 检查基本信息是否完整
    if (!relation.courseGoal) {
      globalCheckResult.value = {
        success: false,
        message: `第${relation.number}项对应关系信息不完整，请检查`
      }
      return
    }
    
    // 检查是否有指标点
    if (!relation.graduationRequirementPoints || relation.graduationRequirementPoints.length === 0) {
      globalCheckResult.value = {
        success: false,
        message: `第${relation.number}项缺少毕业要求指标点，请至少添加一个`
      }
      return
    }
    
    // 检查每个指标点
    for (let j = 0; j < relation.graduationRequirementPoints.length; j++) {
      const point = relation.graduationRequirementPoints[j]
      
      if (!point.graduationRequirementNumber || 
          !point.graduationRequirementDescription ||
          !point.graduationRequirementPointNumber || 
          !point.graduationRequirementPointDescription || 
          !point.supportLevel) {
        globalCheckResult.value = {
          success: false,
          message: `第${relation.number}项第${j + 1}个指标点信息不完整，请检查`
        }
        return
      }
      
      // 检查毕业要求指标点编号格式和匹配关系
      const pointPattern = /^\d+\.\d+$/
      if (!pointPattern.test(point.graduationRequirementPointNumber)) {
        globalCheckResult.value = {
          success: false,
          message: `第${relation.number}项第${j + 1}个指标点格式应为 x.y 的形式，如 3.2`
        }
        return
      }
      
      const pointMainNumber = parseInt(point.graduationRequirementPointNumber.split('.')[0])
      if (pointMainNumber !== point.graduationRequirementNumber) {
        globalCheckResult.value = {
          success: false,
          message: `第${relation.number}项第${j + 1}个指标点 ${point.graduationRequirementPointNumber} 与毕业要求 ${point.graduationRequirementNumber} 不匹配`
        }
        return
      }
      
      // 检查重复
      if (checkPointNumberDuplicate(point.graduationRequirementPointNumber, i, j)) {
        globalCheckResult.value = {
          success: false,
          message: `第${relation.number}项第${j + 1}个指标点 ${point.graduationRequirementPointNumber} 已存在，不能重复`
        }
        return
      }
    }
  }
  
  globalCheckResult.value = {
    success: true,
    message: '检查通过'
  }
}

// 添加评价方法
const addEvaluationMethod = () => {
  const newMethod = {
    number: evaluationMethods.value.length + 1,
    methodName: '',
    isProcessEvaluation: true,
    percentage: null,
    evaluationBasis: '',
    goalWeights: new Array(goalRelations.value.length).fill(0)
  }
  evaluationMethods.value.push(newMethod)
}

// 删除评价方法
const removeEvaluationMethod = (index) => {
  ElMessageBox.confirm('确定要删除这个评价方法吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    evaluationMethods.value.splice(index, 1)
    // 重新排序序号
    evaluationMethods.value.forEach((method, idx) => {
      method.number = idx + 1
    })
    // 清除检查结果和表格
    evaluationCheckResult.value = null
    evaluationTable.value = null
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

// 清空所有评价方法
const clearAllEvaluationMethods = () => {
  if (evaluationMethods.value.length === 0) {
    ElMessage.warning('当前没有评价方法数据')
    return
  }
  
  ElMessageBox.confirm('确定要清空所有评价方法吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定清空',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger'
  }).then(() => {
    evaluationMethods.value = []
    // 清除相关的结果
    evaluationCheckResult.value = null
    evaluationTable.value = null
    ElMessage.success('所有评价方法已清空')
  }).catch(() => {
    // 用户取消清空
  })
}

// 检查评价方法
const checkEvaluationMethods = () => {
  if (evaluationMethods.value.length === 0) {
    evaluationCheckResult.value = {
      success: false,
      message: '请先添加评价方法'
    }
    return
  }
  
  // 检查每个评价方法是否完整
  for (let i = 0; i < evaluationMethods.value.length; i++) {
    const method = evaluationMethods.value[i]
    
    if (!method.methodName) {
      evaluationCheckResult.value = {
        success: false,
        message: `第${method.number}项缺少评价方法名称`
      }
      return
    }
    
    if (method.isProcessEvaluation === null || method.isProcessEvaluation === undefined) {
      evaluationCheckResult.value = {
        success: false,
        message: `第${method.number}项请选择是否过程性考核`
      }
      return
    }
    
    if (method.percentage === null || method.percentage === undefined) {
      evaluationCheckResult.value = {
        success: false,
        message: `第${method.number}项缺少比例`
      }
      return
    }
    
    if (method.percentage < 0 || method.percentage > 100) {
      evaluationCheckResult.value = {
        success: false,
        message: `第${method.number}项比例必须在0-100之间`
      }
      return
    }
    
    if (!Number.isInteger(method.percentage)) {
      evaluationCheckResult.value = {
        success: false,
        message: `第${method.number}项比例必须是整数`
      }
      return
    }
    
    if (!method.evaluationBasis) {
      evaluationCheckResult.value = {
        success: false,
        message: `第${method.number}项缺少评价依据`
      }
      return
    }
    
    // 检查目标点比重
    if (!method.goalWeights || method.goalWeights.length !== goalRelations.value.length) {
      evaluationCheckResult.value = {
        success: false,
        message: `第${method.number}项目标点比重数据不完整`
      }
      return
    }
    
    const goalWeightsTotal = getGoalWeightsTotal(method.goalWeights)
    if (goalWeightsTotal !== 100) {
      evaluationCheckResult.value = {
        success: false,
        message: `第${method.number}项目标点比重总和为${goalWeightsTotal}%，应该等于100%`
      }
      return
    }
  }
  
  // 检查比例总和是否等于100
  const totalPercentage = evaluationMethods.value.reduce((sum, method) => sum + (method.percentage || 0), 0)
  if (totalPercentage !== 100) {
    evaluationCheckResult.value = {
      success: false,
      message: `所有评价方法的比例总和为${totalPercentage}%，应该等于100%`
    }
    return
  }
  
  evaluationCheckResult.value = {
    success: true,
    message: '检查通过'
  }
}

// 生成评价方法表格
const generateEvaluationTable = () => {
  // 生成总评成绩公式
  const formulaParts = evaluationMethods.value.map(method => 
    `${method.methodName}${method.percentage}%`
  )
  totalEvaluationFormula.value = formulaParts.join('+')
  
  evaluationTable.value = true
  ElMessage.success('评价方法表格生成成功')
}

// 计算目标点比重总和
const getGoalWeightsTotal = (goalWeights) => {
  return goalWeights.reduce((sum, weight) => sum + (weight || 0), 0)
}

// 验证目标点比重
const validateGoalWeights = (methodIndex) => {
  const method = evaluationMethods.value[methodIndex]
  const total = getGoalWeightsTotal(method.goalWeights)
  
  if (total !== 100) {
    // 可以在这里添加额外的验证逻辑
    // console.log(`评价方法 ${method.methodName} 的目标点比重总和为 ${total}%，不等于100%`)
  }
}

// 生成课程目标与毕业要求指标点对应表
const generateCorrespondenceTable = () => {
  // 计算支撑度总值（所有指标点的支撑度总和）
  const supportLevelValues = {
    'H': 3,
    'M': 2,
    'L': 1
  }
  
  let totalValue = 0
  goalRelations.value.forEach(goal => {
    if (goal.graduationRequirementPoints) {
      goal.graduationRequirementPoints.forEach(point => {
        if (point.supportLevel && supportLevelValues[point.supportLevel]) {
          totalValue += supportLevelValues[point.supportLevel]
        }
      })
    }
  })
  
  // 检查是否有有效的支撑度值
  if (totalValue === 0) {
    ElMessage.error('总支撑度值为0，请检查指标点的支撑度设置')
    return
  }
  
  // 计算每个课程目标的权重（该目标下所有指标点的支撑度总和 / 总支撑度）
  goalRelations.value.forEach(goal => {
    let goalTotalValue = 0
    if (goal.graduationRequirementPoints) {
      goal.graduationRequirementPoints.forEach(point => {
        if (point.supportLevel && supportLevelValues[point.supportLevel]) {
          goalTotalValue += supportLevelValues[point.supportLevel]
        }
      })
    }
    goal.weight = (goalTotalValue / totalValue).toFixed(2)
  })
  
  correspondenceTable.value = true
  ElMessage.success('课程目标与毕业要求指标点对应表生成成功')
}

// 下载模板
const downloadTemplate = () => {
  if (evaluationMethods.value.length === 0) {
    ElMessage.warning('请先添加评价方法')
    return
  }
  
  if (goalRelations.value.length === 0) {
    ElMessage.warning('请先添加课程目标与毕业要求的对应关系')
    return
  }
  
  // 动态导入xlsx库
  import('xlsx').then(XLSX => {
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    
    // 准备表头数据 - 新的格式：评价方法$目标序号
    const headers = []
    evaluationMethods.value.forEach(method => {
      goalRelations.value.forEach(goal => {
        headers.push(`${method.methodName}$目标${goal.number}`)
      })
    })
    
    // 创建工作表数据（至少包含一行数据以确保格式正确）
    const wsData = [headers]
    
    // 创建工作表
    const ws = XLSX.utils.aoa_to_sheet(wsData)
    
    // 设置数值格式（除第一行外的所有单元格）
    const range = XLSX.utils.decode_range(ws['!ref'])
    for (let R = range.s.r + 1; R <= range.e.r; R++) {
      for (let C = range.s.c; C <= range.e.c; C++) {
        const cellAddress = XLSX.utils.encode_cell({ r: R, c: C })
        if (!ws[cellAddress]) {
          ws[cellAddress] = { v: 0, t: 'n' }
        }
        ws[cellAddress].t = 'n' // 设置为数值格式
      }
    }
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, 'sheet1')
    
    // 生成文件名
    const fileName = `${courseInfo.courseName}达成度导入模板.xlsx`
    
    // 下载文件
    XLSX.writeFile(wb, fileName)
    
    ElMessage.success('模板下载成功')
  }).catch(error => {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败，请检查xlsx库是否正确安装')
  })
}

// 处理文件上传
const handleFileChange = (file) => {
  if (!file.raw) {
    ElMessage.error('文件读取失败')
    return
  }
  
  // 检查文件格式
  if (!file.raw.name.endsWith('.xlsx')) {
    ElMessage.error('请上传xlsx格式的文件')
    return
  }
  
  // 动态导入xlsx库
  import('xlsx').then(XLSX => {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        
        // 检查sheet名称
        if (!workbook.SheetNames.includes('sheet1')) {
          ElMessage.error('请确保sheet名称为"sheet1"')
          return
        }
        
        const worksheet = workbook.Sheets['sheet1']
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
        
        if (jsonData.length === 0) {
          ElMessage.error('文件内容为空')
          return
        }
        
        // 处理数据并计算达成度
        processAchievementData(jsonData)
        
      } catch (error) {
        console.error('文件处理失败:', error)
        ElMessage.error('文件处理失败，请检查文件格式')
      }
    }
    reader.readAsArrayBuffer(file.raw)
  }).catch(error => {
    console.error('xlsx库加载失败:', error)
    ElMessage.error('xlsx库加载失败，请检查依赖是否正确安装')
  })
}

// 处理达成度数据
const processAchievementData = (data) => {
  try {
    // 获取表头（第一行）
    const headers = data[0]
    
    // 验证表头是否包含所有需要的列（评价方法$目标序号格式）
    const expectedHeaders = []
    evaluationMethods.value.forEach(method => {
      goalRelations.value.forEach(goal => {
        expectedHeaders.push(`${method.methodName}$目标${goal.number}`)
      })
    })
    
    const missingHeaders = expectedHeaders.filter(header => !headers.includes(header))
    if (missingHeaders.length > 0) {
      ElMessage.error(`缺少列：${missingHeaders.join(', ')}`)
      return
    }
    
    // 处理数据行（跳过表头）
    const dataRows = data.slice(1).filter(row => row.length > 0)
    
    if (dataRows.length === 0) {
      ElMessage.error('没有有效的数据行')
      return
    }
    
    // 计算各课程目标在各评价方法中的平均分
    const goalMethodAverages = {}
    evaluationMethods.value.forEach(method => {
      goalMethodAverages[method.methodName] = {}
      goalRelations.value.forEach(goal => {
        const headerName = `${method.methodName}$目标${goal.number}`
        const columnIndex = headers.indexOf(headerName)
        const scores = dataRows.map(row => {
          const score = parseFloat(row[columnIndex]) || 0
          return score
        }).filter(score => score > 0) // 过滤掉0分和无效数据
        
        if (scores.length > 0) {
          goalMethodAverages[method.methodName][goal.number] = scores.reduce((sum, score) => sum + score, 0) / scores.length
        } else {
          goalMethodAverages[method.methodName][goal.number] = 0
        }
      })
    })
    
    // 计算各评价方法权重
    const methodWeights = {}
    evaluationMethods.value.forEach(method => {
      methodWeights[method.methodName] = (method.percentage / 100).toFixed(2)
    })
    
    // 计算课程目标达成值
    const goalAchievements = goalRelations.value.map(goal => {
      const methodResults = {}
      let totalAverageScore = 0  // 课程目标平均得分
      let totalTargetScore = 0   // 课程目标总分
      
      evaluationMethods.value.forEach(method => {
        const goalAverageScore = goalMethodAverages[method.methodName][goal.number] || 0
        const weight = parseFloat(methodWeights[method.methodName]) || 0
        const goalWeight = method.goalWeights[goal.number - 1] || 0
        
        // 累加课程目标平均得分（平均分 * 权重）
        totalAverageScore += goalAverageScore * weight
        
        // 累加课程目标总分（目标值 * 权重）
        totalTargetScore += goalWeight * weight
        
        methodResults[method.methodName] = {
          targetValue: goalWeight, // 使用评价方法中设置的课程目标比重
          averageScore: goalAverageScore.toFixed(2), // 该课程目标在该评价方法中的平均分
          weight: weight
        }
      })
      
      // 计算课程分目标达成值：课程目标平均得分 / 课程目标总分
      const achievementValue = totalTargetScore > 0 ? (totalAverageScore / totalTargetScore) : 0
      
      return {
        ...goal,
        methodResults,
        achievementValue: achievementValue.toFixed(2)
      }
    })
    
    // 计算整体课程目标达成度（新的计算方法）
    // 使用各课程目标的达成值乘以对应的支撑度权重
    const supportLevelValues = { 'H': 3, 'M': 2, 'L': 1 }
    
    // 计算所有指标点的总支撑度值
    let totalSupportValue = 0
    goalRelations.value.forEach(goal => {
      if (goal.graduationRequirementPoints) {
        goal.graduationRequirementPoints.forEach(point => {
          if (point.supportLevel && supportLevelValues[point.supportLevel]) {
            totalSupportValue += supportLevelValues[point.supportLevel]
          }
        })
      }
    })
    
    // 检查是否有有效的支撑度值
    if (totalSupportValue === 0) {
      console.error('总支撑度值为0，请检查指标点的支撑度设置')
      ElMessage.error('总支撑度值为0，请检查指标点的支撑度设置')
      return
    }
    
    // 计算整体达成度：每个指标点的达成度 * 该指标点的支撑度权重
    let overallAchievementValue = 0
    goalAchievements.forEach(goal => {
      const goalAchievement = parseFloat(goal.achievementValue)
      if (isNaN(goalAchievement)) {
        console.error(`课程目标${goal.number}的达成度计算失败:`, goal.achievementValue)
        return
      }
      
      if (goal.graduationRequirementPoints) {
        goal.graduationRequirementPoints.forEach(point => {
          if (point.supportLevel && supportLevelValues[point.supportLevel]) {
            const pointWeight = supportLevelValues[point.supportLevel] / totalSupportValue
            const contribution = goalAchievement * pointWeight
            overallAchievementValue += contribution
          }
        })
      }
    })
    
    // 更新结果
    goalResults.value = goalAchievements
    processedEvaluationMethods.value = evaluationMethods.value.map(method => ({
      ...method,
      id: method.number,
      targetValue: '', // 目标值在每行数据中单独计算，这里不需要
      averageScore: (goalMethodAverages[method.methodName] ? 
        Object.values(goalMethodAverages[method.methodName]).reduce((sum, score) => sum + score, 0) / Object.keys(goalMethodAverages[method.methodName]).length : 0).toFixed(2), // 该评价方法下所有课程目标的平均分
      weight: methodWeights[method.methodName]
    }))
    overallAchievement.value = overallAchievementValue.toFixed(2)
    
    // 保存学生原始数据用于图表绘制
    studentData.value = dataRows
    dataHeaders.value = headers // 保存表头信息
    
    ElMessage.success('达成度计算完成')
    
  } catch (error) {
    console.error('达成度计算失败:', error)
    ElMessage.error('达成度计算失败，请检查数据格式')
  }
}

// 生成AI提示词
const generateAIPrompts = () => {
  // 检查课程基本信息是否完整
  if (!courseInfo.courseName || !courseInfo.applicableMajor) {
    ElMessage.error('请先完善课程基本信息中的课程名称和适用专业')
    return
  }
  
  // 检查是否有课程目标对应关系
  if (goalRelations.value.length === 0) {
    ElMessage.error('请先添加课程目标与毕业要求的对应关系')
    return
  }
  
  // 检查每个对应关系是否完整
  for (let i = 0; i < goalRelations.value.length; i++) {
    const relation = goalRelations.value[i]
    if (!relation.courseGoal || !relation.graduationRequirementNumber || 
        !relation.graduationRequirementDescription) {
      ElMessage.error(`第${relation.number}项对应关系信息不完整，请检查`)
      return
    }
    
    // 检查指标点是否完整
    if (!relation.graduationRequirementPoints || relation.graduationRequirementPoints.length === 0) {
      ElMessage.error(`第${relation.number}项缺少毕业要求指标点，请至少添加一个`)
      return
    }

    for (let j = 0; j < relation.graduationRequirementPoints.length; j++) {
      const point = relation.graduationRequirementPoints[j]
      if (!point.graduationRequirementNumber || 
          !point.graduationRequirementDescription ||
          !point.graduationRequirementPointNumber || 
          !point.graduationRequirementPointDescription || 
          !point.supportLevel) {
        ElMessage.error(`第${relation.number}项第${j + 1}个指标点信息不完整，请检查`)
        return
      }
    }
  }
  
  generating.value = true
  
  // 模拟异步操作
  setTimeout(() => {
    aiPrompts.value = goalRelations.value.map(relation => {
      const promptText = `我是${courseInfo.applicableMajor}的高校教师，在教授《${courseInfo.courseName}》这门课程，现在我要对课程目标${relation.number}（${relation.courseGoal}）设计评分标准，请分别给出优秀（90-100分）、良好（80-89分）、中等（70-79分）、及格（60-69分）、不及格（60分以下）的评价标准，每个标准一句话说明即可。`
      
      return {
        goalNumber: relation.number,
        text: promptText
      }
    })
    
    generating.value = false
    ElMessage.success('AI提示词生成成功')
  }, 1000)
}

// 复制提示词
const copyPrompt = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('复制成功')
  } catch (err) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('复制成功')
  }
}

// 保存数据到localStorage
const saveToLocalStorage = () => {
  const data = {
    courseInfo,
    goalRelations: goalRelations.value,
    evaluationMethods: evaluationMethods.value
  }
  localStorage.setItem('courseGoalData', JSON.stringify(data))
}

// 从localStorage加载数据
const loadFromLocalStorage = () => {
  const savedData = localStorage.getItem('courseGoalData')
  if (savedData) {
    try {
      const data = JSON.parse(savedData)
      Object.assign(courseInfo, data.courseInfo)
      
      // 处理旧数据格式的兼容性
      const processedGoalRelations = (data.goalRelations || []).map(relation => {
        // 如果是旧格式（没有 graduationRequirementPoints 数组），转换为新格式
        if (!relation.graduationRequirementPoints) {
          return {
            ...relation,
            graduationRequirementPoints: relation.graduationRequirementPointNumber ? [{
              id: Date.now() + Math.random(),
              graduationRequirementNumber: relation.graduationRequirementNumber,
              graduationRequirementDescription: relation.graduationRequirementDescription || '',
              graduationRequirementPointNumber: relation.graduationRequirementPointNumber,
              graduationRequirementPointDescription: relation.graduationRequirementPointDescription || '',
              supportLevel: relation.supportLevel || '',
              pointNumberError: ''
            }] : []
          }
        }
        // 如果是新格式但指标点缺少毕业要求信息，补充默认值
        if (relation.graduationRequirementPoints) {
          relation.graduationRequirementPoints.forEach(point => {
            if (!point.graduationRequirementNumber && relation.graduationRequirementNumber) {
              point.graduationRequirementNumber = relation.graduationRequirementNumber
            }
            if (!point.graduationRequirementDescription && relation.graduationRequirementDescription) {
              point.graduationRequirementDescription = relation.graduationRequirementDescription
            }
          })
        }
        return relation
      })
      
      goalRelations.value = processedGoalRelations
      evaluationMethods.value = data.evaluationMethods || []
    } catch (error) {
      console.error('加载本地数据失败:', error)
    }
  }
}

// 监听数据变化，自动保存
watch([courseInfo, goalRelations, evaluationMethods], () => {
  saveToLocalStorage()
}, { deep: true })

// 监听课程目标数量变化，更新评价方法的目标点比重
watch(goalRelations, (newGoalRelations) => {
  const goalCount = newGoalRelations.length
  
  // 更新所有评价方法的目标点比重数组
  evaluationMethods.value.forEach(method => {
    if (!method.goalWeights) {
      method.goalWeights = new Array(goalCount).fill(0)
    } else if (method.goalWeights.length !== goalCount) {
      // 如果课程目标数量变化，调整数组长度
      if (method.goalWeights.length < goalCount) {
        // 增加课程目标，在数组末尾添加0
        while (method.goalWeights.length < goalCount) {
          method.goalWeights.push(0)
        }
      } else {
        // 减少课程目标，截取数组
        method.goalWeights = method.goalWeights.slice(0, goalCount)
      }
    }
  })
}, { deep: true })

// 监听达成标准变化
watch(achievementStandard, (newValue) => {
  console.log('CalcGoal: 达成标准已更新为:', newValue)
  // 强制重新计算达成度结果，确保GoalAudit组件能够正确响应
  if (goalResults.value.length > 0) {
    // 触发响应式更新
    goalResults.value = [...goalResults.value]
  }
})

// 组件挂载时加载数据
onMounted(() => {
  loadFromLocalStorage()
})
</script>

<style scoped>
.calc-goal-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.section-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.goal-relation-item {
  margin-bottom: 20px;
}

.relation-card {
  border: 1px solid #e4e7ed;
}

.relation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.relation-number {
  font-weight: bold;
  color: #409eff;
}

.scoring-section {
  text-align: center;
}

.prompts-container {
  margin-top: 30px;
  text-align: left;
}

.prompts-container h3 {
  margin-bottom: 20px;
  color: #303133;
}

.prompt-item {
  margin-bottom: 20px;
}

.prompt-card {
  border: 1px solid #e4e7ed;
}

.prompt-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.prompt-content {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #606266;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-card__header) {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.global-check-section {
  margin-bottom: 20px;
  text-align: center;
}

.global-check-result {
  margin-top: 10px;
}

.check-section {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

.check-result {
  margin-top: 10px;
}

.check-success {
  color: #67c23a;
  font-weight: 500;
}

.check-error {
  color: #f56c6c;
  font-weight: 500;
}

.evaluation-method-item {
  margin-bottom: 20px;
}

.method-card {
  border: 1px solid #e4e7ed;
}

.method-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.method-number {
  font-weight: bold;
  color: #409eff;
}

.evaluation-check-section {
  margin: 20px 0;
  text-align: center;
}

.evaluation-check-result {
  margin-top: 10px;
}

.generate-table-section {
  margin: 20px 0;
  text-align: center;
}

.generate-correspondence-table-section {
  margin: 20px 0;
  text-align: center;
}

.add-relation-section {
  margin: 20px 0;
  text-align: center;
}

.add-evaluation-method-section {
  margin: 20px 0;
  text-align: center;
}

.correspondence-table-container {
  margin-top: 30px;
}

.correspondence-table-container h3 {
  margin-bottom: 20px;
  color: #303133;
}

.evaluation-table-container {
  margin-top: 30px;
}

.evaluation-table-container h3 {
  margin-bottom: 20px;
  color: #303133;
}

.table-wrapper {
  overflow-x: auto;
}

.evaluation-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid black;
}

.evaluation-table th,
.evaluation-table td {
  border: 1px solid black;
  padding: 12px;
  text-align: center;
  vertical-align: middle;
}

.evaluation-table th {

  font-weight: bold;
  color: #303133;
}

.process-evaluation-cell {
  font-weight: 500;
}

.total-row {

  font-weight: bold;
}

.total-row td {
  color: #303133;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.correspondence-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid black;
}

.correspondence-table th,
.correspondence-table td {
  border: 1px solid black;
  padding: 12px;
  text-align: left;
  vertical-align: top;
}

.correspondence-table th {
  font-weight: bold;
  color: black;
  background-color: white;
}

.correspondence-table td {
  color: black;
  background-color: white;
}

.goal-weights-table-container {
  margin-top: 10px;
}

.goal-weights-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e4e7ed;
  margin-bottom: 10px;
}

.goal-weights-table th,
.goal-weights-table td {
  border: 1px solid #e4e7ed;
  padding: 8px;
  text-align: left;
  vertical-align: middle;
}

.goal-weights-table th {
  background-color: #f8f9fa;
  font-weight: bold;
  color: #303133;
}

.goal-weights-table td:first-child {
  width: 70%;
}

.goal-weights-table td:last-child {
  width: 30%;
  text-align: center;
}

.goal-weights-total {
  font-size: 14px;
  color: #606266;
  text-align: right;
  margin-top: 5px;
}

.weight-error {
  color: #f56c6c;
  font-weight: 500;
}

.achievement-calculation-section {
  padding: 20px 0;
}

.file-operations {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin-bottom: 30px;
}

.upload-button {
  display: inline-block;
}

.upload-tips {
  background-color: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 30px;
}

.upload-tips h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.upload-tips ul {
  margin: 0;
  padding-left: 20px;
}

.upload-tips li {
  margin-bottom: 8px;
  color: #606266;
  line-height: 1.5;
}

.achievement-charts-section {
  padding: 20px 0;
}

.charts-prerequisite {
  margin-bottom: 20px;
  text-align: center;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-section h3 {
  margin-bottom: 10px;
  color: #303133;
}

.goal-audit-section {
  padding: 20px 0;
}

.audit-prerequisite {
  margin-bottom: 20px;
  text-align: center;
}

.graduation-requirement-point-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #fafafa;
  width: 100%;
  box-sizing: border-box;
}

.point-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.point-number {
  font-weight: bold;
  color: #409eff;
  font-size: 14px;
}

.graduation-requirement-point-item .el-form-item {
  margin-bottom: 10px;
}

.graduation-requirement-point-item .el-form-item__label {
  font-size: 12px;
  color: #606266;
}

.point-content {
  padding: 15px 0;
  width: 100%;
}

.point-field {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  padding: 0 10px;
  width: 100%;
}

.point-field:last-child {
  margin-bottom: 0;
}

.field-label {
  min-width: 120px;
  max-width: 120px;
  font-weight: 500;
  color: #303133;
  font-size: 14px;
  line-height: 32px;
  margin-right: 15px;
  text-align: right;
  flex-shrink: 0;
}

.point-field .el-input,
.point-field .el-input-number,
.point-field .el-textarea {
  flex: 1;
  min-width: 0;
}

.point-field .el-radio-group {
  flex: 1;
  display: flex;
  align-items: center;
  min-width: 0;
}

.point-field .el-radio {
  margin-right: 30px;
}

.point-field .el-radio:last-child {
  margin-right: 0;
}

.table-point-item {
  margin-bottom: 8px;
  padding: 5px 0;
  border-bottom: 1px solid #f0f0f0;
}

.table-point-item:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.point-main {
  font-weight: 500;
  color: #303133;
  margin-bottom: 3px;
}

.point-support {
  font-size: 12px;
  color: #909399;
}

.table-requirement-item {
  margin-bottom: 5px;
  padding: 3px 0;
  color: #606266;
}

.table-requirement-item:last-child {
  margin-bottom: 0;
}

.button-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.add-point-button-container {
  margin-top: 15px;
  padding: 10px 0;
  text-align: center;
  border-top: 1px solid #e4e7ed;
}
</style>
